package com.futures.investm.common;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.futures.investm.Config;
import com.futures.investm.R;
import com.futures.investm.constant.BussConstant;
import com.futures.investm.event.MineEvent;
import com.futures.investm.event.UpdateUserInfoEvent;
import com.futures.investm.utils.AppUtil;
import com.futures.investm.utils.CacheData;
import com.futures.investm.utils.IntentUtils;
import com.futures.investm.utils.PhotoUtils;
import com.aries.ui.view.radius.RadiusEditText;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.SaveCallback;
import com.vise.xsnow.event.BusManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.manager.GlideManager;
import tech.com.commoncore.manager.LoggerManager;
import tech.com.commoncore.utils.FastUtil;
import tech.com.commoncore.utils.FileUtils;
import tech.com.commoncore.utils.SizeUtil;
import tech.com.commoncore.utils.StackUtil;
import tech.com.commoncore.utils.ToastUtil;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.content.DialogInterface.BUTTON_NEGATIVE;
import static android.content.DialogInterface.BUTTON_NEUTRAL;
import static android.content.DialogInterface.BUTTON_POSITIVE;

public class UserActivity extends BaseTitleActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.ll_head)
    LinearLayout ll_head;//头像
    @BindView(R.id.ll_user_name)
    LinearLayout ll_user_name;//昵称
    @BindView(R.id.ll_change_pw)//重置密码
            LinearLayout ll_change_pw;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    //    @BindView(R.id.tv_signature)
//    TextView tvSignature;
    @BindView(R.id.iv_userHead)
    ImageView ivUserHead;

    @BindView(R.id.btn_sign_out)
    Button btn_sign_out;

    public static final int RC_CAMERA_PERMISSIONS = 111;
    public static final int RC_ALBUM_PERMISSIONS = 222;
    public static final int RC_CAMERA = 333;
    public static final int RC_ALBUM = 444;
    public static final int RC_CROP = 555;


    private String[] permsCamera = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String[] permsAlbum = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private AlertDialog picDialog;
    private File tempFile;
    protected File tempCropFile;
    private File dirFile;

    private AVUser mUser;

    @OnClick({R.id.ll_head, R.id.ll_user_name, R.id.ll_change_pw, R.id.btn_sign_out})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_head:
                showPhotoDialog();
                break;
            case R.id.ll_user_name:
                showNickNameDialog();
                break;
            case R.id.ll_change_pw:
                IntentUtils.goChangePassword(mContext);
                break;
            case R.id.btn_sign_out:
                //退出
                getSignOut();
                break;
        }
    }


    //登出
    private void getSignOut() {
        AVUser.logOut();// 清除缓存用户对象
        //清除登录信息
        CacheData.setLoginUserId(mContext, "");
        CacheData.setLoginUser(null);
        CacheData.setLoginPassword(mContext, "");
        FastUtil.startActivity(mContext, LoginActivity.class);
        StackUtil.getInstance().popAllExceptCurrent(LoginActivity.class);
    }

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText("个人信息")
                .setOnLeftTextClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onBackPressed();
                    }
                })
                .setStatusBarLightMode(false);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_user;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        mUser = CacheData.getLoginUser();

        if (mUser != null) {
            GlideManager.loadCircleImg(mUser.get(BussConstant.HEAD_URL), ivUserHead, R.mipmap.logo);
            tvNickname.setText(mUser.getString(BussConstant.NICKNAME));
//            tvSignature.setText(mUser.getString(BussConstant.SIGNATURE));
        }

        initPhotoPicker();

    }


    private void initPhotoPicker() {
        dirFile = new File(Config.PHOTO_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        initPicDialog();
    }


    private void showNickNameDialog() {
        final RadiusEditText editText = new RadiusEditText(mContext);
        ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //                params.topMargin = SizeUtil.dp2px(12);
        editText.getDelegate()
                .setTextColor(Color.GRAY)
                .setRadius(6f)
                .setBackgroundColor(Color.WHITE)
                .setStrokeColor(Color.GRAY)
                .setStrokeWidth(SizeUtil.dp2px(0.5f));
        editText.setMinHeight(SizeUtil.dp2px(40));
        editText.setGravity(Gravity.CENTER_VERTICAL);
        editText.setPadding(SizeUtil.dp2px(12), 0, SizeUtil.dp2px(12), 0);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        editText.setHint("请输入昵称");
        editText.setText(tvNickname.getText().toString());
        editText.setSelection(editText.getText().length());
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        editText.setLayoutParams(params);
        new UIAlertDialog.DividerIOSBuilder(this)
                .setTitle("设置昵称")
                .setView(editText)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String text = editText.getText().toString().trim();
                        if (TextUtils.isEmpty(text)) {
                            ToastUtil.show("请输入新昵称");
                            return;
                        } else {
                            updateNickName(text);
                        }


                    }
                })
                .create()
                .setDimAmount(0.6f)
                .show();
    }


    //上传头像
    private void upLoadHead(String imgPath) {
        try {
            String fileName = FileUtils.splitFileName(imgPath);
            final AVFile avFile = AVFile.withAbsoluteLocalPath(fileName, imgPath);
            avFile.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        updateHead(avFile.getUrl());
                    } else {
                        ToastUtil.show("图片上传失败");
                    }
                }
            }, new ProgressCallback() {
                @Override
                public void done(Integer integer) {

                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    private void updateHead(final String headUrl) {
        mUser.put(BussConstant.HEAD_URL, headUrl);
        mUser.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    GlideManager.loadCircleImg(headUrl, ivUserHead);
                    LoggerManager.e("headUrl:" + headUrl);
                    CacheData.setLoginUser(mUser);
                    BusManager.getBus().post(new UpdateUserInfoEvent());
                    BusManager.getBus().post(new MineEvent());
                    ToastUtil.show("更改头像成功");
                } else {
                    ToastUtil.show("更改头像失败");
                }
            }
        });
    }

    //更新昵称
    private void updateNickName(final String nickName) {
        mUser.put(BussConstant.NICKNAME, nickName);
        mUser.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    tvNickname.setText(mUser.getString(BussConstant.NICKNAME));
                    CacheData.setLoginUser(mUser);
                    BusManager.getBus().post(new UpdateUserInfoEvent());
                    BusManager.getBus().post(new MineEvent());
                    ToastUtil.show("更改昵称成功");
                } else {
                    ToastUtil.show("更改昵称失败");
                }
            }
        });
    }

    //更新签名
    private void updateSignature(final String signature) {
        AVUser.getCurrentUser().put(BussConstant.SIGNATURE, signature);
        AVUser.getCurrentUser().saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
//                    tvSignature.setText(mUser.getString(BussConstant.SIGNATURE));
                    CacheData.setLoginUser(mUser);
                    ToastUtil.show("更改签名成功");
                } else {
                    ToastUtil.show("更改签名失败");
                }
            }
        });
    }

    public void initPicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String[] items = new String[]{"拍照", "相册"};
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (0 == which) {
                    //拍照
                    EasyPermissions.requestPermissions(mContext, "拍照需要开启相机和存储空间权限", RC_CAMERA_PERMISSIONS, permsCamera);
                } else {
                    //相册
                    EasyPermissions.requestPermissions(mContext, "打开相册需要开启存储空间权限", RC_ALBUM_PERMISSIONS, permsAlbum);
                }
            }
        });
        picDialog = builder.create();
    }

    public void showPhotoDialog() {
        picDialog.show();
    }

    public void doCamera() {
        tempFile = new File(dirFile, System.currentTimeMillis() + ".jpg");
        PhotoUtils.toCamera(this, tempFile, RC_CAMERA);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (RC_ALBUM_PERMISSIONS == requestCode) {
            PhotoUtils.toAlbum(this, RC_ALBUM);
        } else if (RC_CAMERA_PERMISSIONS == requestCode) {
            doCamera();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (RC_CAMERA_PERMISSIONS == requestCode) {
            new UIAlertDialog.DividerIOSBuilder(this)
                    .setTitle("权限申请")
                    .setMessage("在设置-应用-\" + getString(R.string.app_name) + \"-权限中开启相机权限和存储空间权限，以正常使用拍照功能")
                    .setNegativeButton("取消", onAlertClick)
                    .setPositiveButton("去设置", onAlertClick)
                    .setMinHeight(SizeUtil.dp2px(160))
                    .create()
                    .show();
        } else if (RC_ALBUM_PERMISSIONS == requestCode) {
            new UIAlertDialog.DividerIOSBuilder(this)
                    .setTitle("权限申请")
                    .setMessage("在设置-应用-\" + getString(R.string.app_name) + \"-权限中开启存储空间权限，以正常使用相册功能")
                    .setNegativeButton("取消", onAlertClick)
                    .setPositiveButton("去设置", onAlertClick)
                    .setMinHeight(SizeUtil.dp2px(160))
                    .create()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK != resultCode) {
            return;
        }
        if (RC_CAMERA == requestCode) {
            String imgPath = tempFile.getPath();
            if (!TextUtils.isEmpty(imgPath) && tempFile.length() > 0) {
                //展示图片
                if (getNeedCrop()) {
                    //截图
                    tempCropFile = new File(Config.PHOTO_PATH + Long.toString(System.nanoTime()) + "_cropped.jpg");
                    if (tempCropFile.exists()) {
                        tempCropFile.delete();
                    }
                    PhotoUtils.toCrop(this, tempFile, tempCropFile, 0, RC_CROP);
                } else {
                    compressPhoto(requestCode, imgPath);
                    //                    onPhotoCallBack(requestCode, imgPath);
                }
            } else {
                ToastUtil.show("获取拍照照片失败");
            }
        } else if (RC_ALBUM == requestCode) {
            if (data == null) {
                ToastUtil.show("获取相册照片失败");
                return;
            }
            Uri imgUri = data.getData();
            String imgPath = PhotoUtils.uriToPath(this, imgUri);
            File file = new File(imgPath);
            if (!TextUtils.isEmpty(imgPath) && file.exists() && file.length() > 0) {
                if (getNeedCrop()) {
                    //截图
                    tempCropFile = new File(Config.PHOTO_PATH + Long.toString(System.nanoTime()) + "_cropped.jpg");
                    if (tempCropFile.exists()) {
                        tempCropFile.delete();
                    }
                    PhotoUtils.toCrop(this, new File(imgPath), tempCropFile, 0, RC_CROP);
                } else {
                    compressPhoto(requestCode, file.getPath());
                    //                    onPhotoCallBack(requestCode, imgPath);
                }
            } else {
                ToastUtil.show("获取相册照片失败");
            }
        } else if (RC_CROP == requestCode) {
            String imgPath = tempCropFile.getPath();
            if (tempFile != null) {
                tempFile.delete();
            }
            if (!TextUtils.isEmpty(imgPath) && tempCropFile.length() > 0) {
                //展示图片
                compressPhoto(requestCode, imgPath);
                //                onPhotoCallBack(requestCode, imgPath);
            } else {
                ToastUtil.show("获取照片失败");
            }
        }
    }

    /**
     * 压缩图片
     *
     * @param requestCode
     * @param photoPath
     */
    private void compressPhoto(final int requestCode, final String photoPath) {
        Luban.with(this).load(photoPath).ignoreBy(100).setTargetDir(Config.PHOTO_PATH).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(File file) {
                upLoadHead(file.getPath());
            }

            @Override
            public void onError(Throwable e) {
                LoggerManager.e("图片压缩失败" + e.getMessage());
                ToastUtil.show("图片上传失败");
            }
        }).launch();
    }

    protected boolean getNeedCrop() {
        return false;
    }


    private DialogInterface.OnClickListener onAlertClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case BUTTON_NEGATIVE:
                    break;
                case BUTTON_POSITIVE:
                    AppUtil.startAppSettings(UserActivity.this);
                    break;
                case BUTTON_NEUTRAL:
                    break;
            }
        }
    };

}
